package com.shujia.flink.state;

import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.serialization.SimpleStringSchema;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.connector.kafka.source.KafkaSource;
import org.apache.flink.connector.kafka.source.enumerator.initializer.OffsetsInitializer;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

public class Demo4KafkaState {
    public static void main(String[] args) throws Exception {
        //1、创建flink执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        //构建kafka source
        KafkaSource<String> source = KafkaSource.<String>builder()
                //指定broker列表
                .setBootstrapServers("master:9092,node1:9092,node2:9092")
                //指定topic
                .setTopics("words")
                //消费者组
                .setGroupId("my-group")
                //指定读取数据的位置：earliest：读取最早的数据, latest: 读取最新的数据
                .setStartingOffsets(OffsetsInitializer.earliest())
                //读取数据的格式
                .setValueOnlyDeserializer(new SimpleStringSchema())
                .build();

        //使用 kafka source
        DataStreamSource<String> linesDS = env
                .fromSource(source, WatermarkStrategy.noWatermarks(), "Kafka Source");


        //lambda表达式
        DataStream<String> wordsDS = linesDS.flatMap((line, out) -> {
            //将一行切分成一个数组
            String[] split = line.split(",");
            //循环将数据发生到下游
            for (String word : split) {
                //将数据发送到下游
                out.collect(word);
            }
        }, Types.STRING);//指定返回的类型信息

        //转换成kv格式
        //Types.TUPLE(Types.STRING, Types.INT) 指定返回的类型
        DataStream<Tuple2<String, Integer>> kvDS = wordsDS
                .map(word -> Tuple2.of(word, 1), Types.TUPLE(Types.STRING, Types.INT));

        //安装单词进行分组
        KeyedStream<Tuple2<String, Integer>, String> keyByDS = kvDS.keyBy(kv -> kv.f0);

        //统计单词的数量
        DataStream<Tuple2<String, Integer>> countDS = keyByDS.sum(1);
        //打印结果
        countDS.print();
        //启动flink
        env.execute();
    }
}
